package com.example.tabbar.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.tabbar.databinding.ItemSamplingDataBinding
import com.example.tabbar.databinding.ItemSingleDataBinding
import com.junray.usermangement.room.bean.SamplingData
import com.junray.usermangement.room.entity.Measurement

@SuppressLint("SetTextI18n")
class SamplingDataAdapter: RecyclerView.Adapter<SamplingDataAdapter.ViewHolder>() {
    private var items: MutableList<SamplingData> = ArrayList()
    private var selectedPositions: MutableSet<Int> = HashSet() // 用于跟踪选中项的位置
    private var expandedPositions: MutableSet<Int> = HashSet() // 添加展开状态跟踪
    private var cachedMeasurements: MutableMap<Int, List<Measurement>> = HashMap() // 缓存已查询的数据
    private var selectAllListener: ((Boolean) -> Unit)? = null // 添加全选状态监听器
    private var measurementLoadListener: ((SamplingData, Int) -> Unit)? = null // 添加点击监听器
    private var itemClickListener: ((SamplingData) -> Unit)? = null  // 某一条数据整体点击

    private var itemLocationListener: ((Measurement) -> Unit)? = null

    // 设置内部项点击监听器的方法
    fun setOnItemLocationListener(listener: (Measurement) -> Unit) {
        this.itemLocationListener = listener
    }

    // 添加设置点击监听器的方法
    fun setOnItemClickListener(listener: (SamplingData) -> Unit) {
        this.itemClickListener = listener
    }

    // 设置测量数据点击监听器
    fun setOnMeasurementClickListener(listener: (SamplingData, Int) -> Unit) {
        this.measurementLoadListener = listener
    }

    fun setOnItemSelectClickListener(listener: (Boolean) -> Unit) {
        this.selectAllListener = listener
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ItemSamplingDataBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }


    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = items[position]

        holder.roomName.text = item.locationName
        holder.time.text = item.startTime + " - " + item.endTime
        holder.group.text = item.groupName
        holder.flow.text = item.flow.toString()
        holder.air.text = item.air
        // 当文字超长时，跑马灯形式滚动
        holder.roomName.isSelected = true
        val isExpanded = expandedPositions.contains(position)
        holder.isShow.text = if (isExpanded) "收起" else "展开"

        // 检查是否有缓存的测量数据
        val cachedData = cachedMeasurements[position]
        if (isExpanded && cachedData != null) {
            holder.innerAdapter.updateData(cachedData)
            // 当子列表数据加载时，检查父级选中状态并同步到子列表
            if (selectedPositions.contains(position)) {
                holder.innerAdapter.childSelectAll(true)
            }
            holder.samplingDataRecyclerView.visibility = View.VISIBLE
        } else {
            holder.innerAdapter.updateData(emptyList())
            holder.samplingDataRecyclerView.visibility = if (isExpanded) View.VISIBLE else View.GONE
        }

        holder.isShow.setOnClickListener {
            val currentExpanded = expandedPositions.contains(position)

            if (currentExpanded) {
                // 收起
                expandedPositions.remove(position)
                holder.samplingDataRecyclerView.visibility = View.GONE
                holder.isShow.text = "展开"
            } else {
                // 展开
                expandedPositions.add(position)
                holder.isShow.text = "收起"
                // 检查是否有缓存数据
                if (cachedMeasurements[position] != null) {
                    holder.innerAdapter.updateData(cachedMeasurements[position]!!)
                    holder.samplingDataRecyclerView.visibility = View.VISIBLE
                } else {
                    // 请求加载数据
                    holder.samplingDataRecyclerView.visibility = View.VISIBLE
                    measurementLoadListener?.invoke(item, position)

                }
            }
        }

        if (expandedPositions.contains(position) && cachedMeasurements[position] != null) {
            val totalCount = cachedMeasurements[position]?.size ?: 0
            val selectedCount = holder.innerAdapter.getSelectedCount()
            val isAllSelected =
                totalCount > 0 && selectedCount == totalCount
            holder.checkBox.isChecked = isAllSelected
        }


        // 设置选中状态
        holder.checkBox.isChecked = selectedPositions.contains(position)
        // 设置选择状态改变监听器
        holder.checkBox.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                selectedPositions.add(position)
                holder.innerAdapter.childSelectAll(true)

            } else {
                selectedPositions.remove(position)
                if (holder.innerAdapter.getSelectedCount() == holder.innerAdapter.getTotalCount()
                    && holder.innerAdapter.getTotalCount() > 0) {
                    holder.innerAdapter.childSelectAll(false)
                }
            }

            // 检查是否需要更新全选按钮状态
            notifySelectAllStateChanged()
        }

        holder.itemView.setOnClickListener {
            itemClickListener?.invoke(item)
        }
    }
    // 更新指定位置的测量数据
    fun updateMeasurementsAtPosition(position: Int, measurements: List<Measurement>) {
        cachedMeasurements[position] = measurements
        notifyItemChanged(position)
    }

    // 全选/取消全选方法
    fun selectAll(select: Boolean) {
        selectedPositions.clear()
        if (select) {
            // 选中所有项
            for (i in 0 until items.size) {
                selectedPositions.add(i)
            }
        }
        notifyDataSetChanged()
        selectAllListener?.invoke(select)
    }

    // 检查是否全选
    private fun isAllSelected(): Boolean {
        return selectedPositions.size == items.size && items.isNotEmpty()
    }
    // 通知全选状态改变
    private fun notifySelectAllStateChanged() {
        val isAllSelected = isAllSelected()
        selectAllListener?.invoke(isAllSelected)
    }

    override fun getItemCount(): Int {
        return items.size ?: 0
    }

    fun setItems(items: List<SamplingData>?) {
        this.items.clear()
        if (items != null) {
            this.items.addAll( items)
            notifyDataSetChanged()
        }
    }

    fun updateParentSelectionState(position: Int, isChildAllSelected: Boolean) {
        if (isChildAllSelected) {
            selectedPositions.add(position)
        } else {
            selectedPositions.remove(position)
        }
        notifySelectAllStateChanged()
    }

    class ViewHolder(binding: ItemSamplingDataBinding)
        : RecyclerView.ViewHolder(binding.root) {
        var checkBox: CheckBox = binding.isSelect
        var roomName = binding.roomName
        var group:TextView = binding.group
        var flow:TextView = binding.flow
        var air :TextView = binding.airType
        var time :TextView= binding.time
        var isShow: TextView = binding.isShow

        var samplingDataRecyclerView: RecyclerView = binding.samplingData // 添加这一行
        var innerAdapter: InnerDataAdapter = InnerDataAdapter() // 添加内部适配器实例

        init {
            // 初始化内部 RecyclerView
            samplingDataRecyclerView.layoutManager = LinearLayoutManager(itemView.context)
            samplingDataRecyclerView.adapter = innerAdapter
            // 如果需要，可以禁用嵌套滚动以避免冲突
            samplingDataRecyclerView.isNestedScrollingEnabled = false

            innerAdapter.setOnChildSelectionChangedListener { isSelected ->
                // 通知外部监听器子项选中状态已改变

                checkBox.isChecked = isSelected
                // 如果需要同步到 selectedPositions 集合，可以通过接口回调处理
                val parentPosition = adapterPosition
                if (parentPosition != RecyclerView.NO_POSITION) {
                    val parentPosition = adapterPosition
                    if (parentPosition != RecyclerView.NO_POSITION) {
                        checkBox.isChecked = isSelected

                        (itemView.parent as? RecyclerView)?.adapter?.let { adapter ->
                            if (adapter is SamplingDataAdapter) {
                                // 调用适配器的方法更新选中状态
                                adapter.updateParentSelectionState(parentPosition, isSelected)
                            }
                        }
                    }
                }
            }
            innerAdapter.setOnItemLocationListener { measurementId ->
                // 根据ID找到对应的Measurement对象并传递
                val parentPosition = adapterPosition
                if (parentPosition != RecyclerView.NO_POSITION) {
                    val parentAdapter = (itemView.parent as? RecyclerView)?.adapter
                    if (parentAdapter is SamplingDataAdapter) {
                        val cachedData = parentAdapter.cachedMeasurements[parentPosition]
                        cachedData?.find { it.id == measurementId }?.let { measurement ->
                            parentAdapter.itemLocationListener?.invoke(measurement)
                        }
                    }
                }
            }
        }
    }


     class InnerDataAdapter : RecyclerView.Adapter<InnerDataAdapter.InnerViewHolder>() {
         private var innerItems: List<Measurement> = emptyList()
         private var selectedLocation: MutableSet<Int> = HashSet() // 选中的点位
         private var onChildSelectionChanged: ((Boolean) -> Unit)? = null // 添加选中状态变化监听器
         private var itemLocationListener: ((Int) -> Unit)? = null  // 点击每一条点位数据监听器

         fun setOnItemLocationListener(listener: (Int) -> Unit) {
             itemLocationListener = listener
         }
         // 设置子项选中状态变化监听器
         fun setOnChildSelectionChangedListener(listener: (Boolean) -> Unit) {
             this.onChildSelectionChanged = listener
         }

         fun updateData(data: List<Measurement>) { // 根据实际数据类型调整
             this.innerItems = data
             notifyDataSetChanged()
         }

         // 获取选中项数量
         fun getSelectedCount(): Int = selectedLocation.size

         // 获取总项数
         fun getTotalCount(): Int = innerItems.size

         // 全选/取消全选
         fun childSelectAll(select: Boolean) {
             selectedLocation.clear()
             if (select) {
                 for (i in innerItems.indices) {
                     selectedLocation.add(i)
                 }
             }
             notifyDataSetChanged()
             onChildSelectionChanged?.invoke(select)
         }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): InnerViewHolder {
            // 创建内部列表项的布局
            val binding = ItemSingleDataBinding.inflate(LayoutInflater.from(parent.context), parent, false)
            return InnerViewHolder(binding)
        }


        override fun onBindViewHolder(holder: InnerViewHolder, position: Int) {
            // 绑定内部数据
            val item = innerItems[position]
            holder.point.text = item.samplingLoc
            holder.time.text = item.startTime + " - " + item.endTime

            // 设置选中状态
            holder.childLocation.isChecked = selectedLocation.contains(position)

            // 设置选择状态改变监听器
            holder.childLocation.setOnCheckedChangeListener { _, isChecked ->
                if (isChecked) {
                    selectedLocation.add(position)
                } else {
                    selectedLocation.remove(position)
                }

                // 检查是否全部选中
                val isAllSelected = selectedLocation.size == innerItems.size && innerItems.isNotEmpty()
                onChildSelectionChanged?.invoke(isAllSelected)
            }

            holder.itemView.setOnClickListener {
                itemLocationListener?.invoke(item.id)
            }
        }

        override fun getItemCount(): Int = innerItems.size

        inner class InnerViewHolder(binding: ItemSingleDataBinding) : RecyclerView.ViewHolder(binding.root) {
            // 定义内部列表项的视图组件
            val childLocation: CheckBox = binding.isSelect
            val point: TextView = binding.point
            val time: TextView = binding.time
        }
    }

}